<template>
  <ContainerContent
    :loading="loading"
    :pagination="pagination"
    :show-pagination="false"
    :refresh="false"
    :show-footer="false"
    @run="run">
    <template #header-prefix>
      <div class="mb-6">
        <div class="title">缓存规则</div>
        <div class="sub-title">
          默认规则仅适用于新添加的站点，已存在的站点不受影响。
        </div>
      </div>
      <a-divider margin="0" type="dashed" />
    </template>
    <cache-rule-table
      ref="cacheRuleTableRef"
      :maxDisplayRows="12"
      v-model:list="form.list" />
    <a-button
      type="primary"
      class="my-6"
      :loading="saveLoading"
      @click="handleSave">
      保存配置
    </a-button>
  </ContainerContent>
</template>
<script lang="ts" setup>
import type { DefaultRuleListItem } from '@/apis/model/site'
import {
  getApiPresetCacheRule,
  updateApiPresetCacheRule
} from '@/apis/modules/resolve/rule'
import ContainerContent from '@/components/ContentContainer.vue'
import type { CloudFilterBarState } from '@/components/filter-bar/types'
import { useListRequest } from '@/hooks/useListRequest'
import CacheRuleTable from '@/views/site/components/CacheRuleTable/CacheRuleTable.vue'
import { cloneDeep } from 'lodash-es'
const cacheRuleTableRef = ref<InstanceType<typeof CacheRuleTable>>()
const queryParams = ref<CloudFilterBarState>({})
interface IList extends DefaultRuleListItem {
  cache_unit: string
}
const form = ref<{ list: IList[] }>({
  list: []
})
const { loading, run, pagination } = useListRequest(getApiPresetCacheRule, {
  params: queryParams,
  immediate: true,
  afterFn: (res) => {
    form.value.list = res.list
    form.value.list.forEach((item: any) => {
      if (item.suffix.length) {
        item.suffix = item.suffix.join(',')
        const cacheData = separateNumberAndLetter(item.cache_time)
        item.cache_time = Number(cacheData.value)
        item.cache_unit = cacheData.unit
      } else {
        item.cache_time = 60
        item.suffix = ''
        item.cache_unit = 's'
      }
    })
  }
})
const saveLoading = ref(false)
const handleSave = async () => {
  const err1 = await cacheRuleTableRef.value?.validateFn()
  if (!err1) return
  saveLoading.value = true
  const list = cloneDeep(form.value.list)
  list.forEach((item) => {
    item.suffix = item?.suffix?.split(',') ?? []
    item.cache_time = item.cache_time + item.cache_unit
    delete item.cache_unit
  })
  await updateApiPresetCacheRule({ list })
    .then(() => {
      ToastUtils.success('操作成功')
      run()
    })
    .finally(() => {
      saveLoading.value = false
    })
}
</script>

<style lang="less" scoped>
.title {
  @apply text-1 text-sm/22px font-bold;
}
.sub-title {
  @apply text-5 text-xs/5;
}
</style>
